package com.mc.string;

public class DoubleReverse {
    public String ReverseSentence(String str) {
        StringBuilder sb = new StringBuilder(str);
        if(str==null)
            return null;
        if(str.length()==0)
        	return str;
        reverse(sb,0,str.length()-1);
        int k = 0;
        for(int i=0;i<str.length();i++){
            if(sb.charAt(i)==' '){
				reverse(sb,k,i-1);              
            	k = i+1;
            }
        }
        if(sb.charAt(str.length()-1)!=' ')reverse(sb,k,str.length()-1);
        
        return sb.toString();
    }
    
    
    public void reverse(StringBuilder sb, int start,int end){
        while(start<end){
            char a  = sb.charAt(start);
            char b  = sb.charAt(end);
            sb.setCharAt(start,b);
            sb.setCharAt(end,a);
            start++;
            end--;
        }
    }
    public static void main(String[] args) {
		DoubleReverse d = new DoubleReverse();
		String res = d.ReverseSentence("abcd efhj dsd! ");
		System.out.println(res);
	}
}
